import requests, json, hashlib, datetime, calendar
from datetime import datetime as diuu


class OpenPlatformDemo(object):  # 接入猫酷平台

    def __init__(self):
        '''
        开发者应用账号，由猫酷提供
        '''
        self.appID = '5e706de04bae7027f4d0c117'  # AppID
        self.publicKey = 'ITkokc'  # 公钥
        self.privateKey = 'f895a1116539ce09'  # 私钥

    def mallcoo_post(self, url, json_data):
        '''
        :param url: 请求url
        :param post_data: 请求参数（json格式）
        :return: Response object
        '''

        timestamp = diuu.now().strftime('%Y%m%d%H%M%S')  # 时间戳

        encryptString = "{publicKey:" + self.publicKey + ",timeStamp:" + timestamp + ",data:" + json.dumps(
            json_data) + ",privateKey:" + self.privateKey + "}"  # 待加密字符串

        sign = hashlib.md5(encryptString.encode(encoding='utf-8')).hexdigest()[8:24].upper()  # 16位MD5加密（大写）

        headers = {
            'Content-Type': 'application/json;charset=utf-8',
            'AppID': self.appID,
            'PublicKey': self.publicKey,
            'TimeStamp': timestamp,
            'Sign': sign
        }
        session = requests.session()

        response = session.post(url, json=json_data, headers=headers)

        return response


def mallsession():  # 请求信息
    url = "https://passport.mp.mallcoo.cn/Home/PostLogin"
    payload = 'isCrossDomain=false&ispersistent=true&password=8d66b556cf62879d1215e5ce82aeb846&username=lyggywy'

    headers = {
        'Accept': '*/*',
        'X-Requested-With': 'XMLHttpRequest',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_0_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Sec-Fetch-Site': 'same-origin',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Dest': 'empty',
        'Cookie': 'acw_tc=707c9fdc16057551818813416e61051b2e67c7888c377a6844ee8ba801bbce; login_parm=GoSTLkGizMGQIJBwPiBHGoLNsNv7a2Ght1BLQe+mHVSjCxbk+kcZuT70ztFn/iQBLCa59ASqCmY=; mp_session=9A96C0535C4D681CFF77170F11F6E75A9DB73C286D249356C47B69390AE6D0C7B44A439AE85147E07AA6BDA10978BAE58B957D6FDC91F261; mp.mallcoo.cn=0CE597CC2A24AB34CCF51B3B472766E29123D09502CDAE6409C186D6A1CFEEF8AE44816163179AF3E4F0BB1A7E81589387385FCE5540435EF4CC22E9286CFED3D024DD0629FBD059E730958A384BEEE84C9BCECC4210B6992F6FA37776842AF83132324E47AF6BAFF93A38F70DE14B9D60332C15D46B0093FB7E983CC2989257113650397DE0ADF56075698740AF9FE869908DA4CBFF3AE810F4C3E4C083DE44238CB69A'
    }
    session = requests.session()
    session.post(url, headers=headers, data=payload)
    return session


def Active_member():  # 获取本月真活跃会员接口数据
    url = 'https://openapi10.mallcoo.cn/BI/BookMark/v1/Get/AttributeResult/'
    json_data = {
        "param": "{\"ProjectId\":552,\"APIId\":\"5e70422ef90e542d18686eea\",\"StartDate\":\"2020-07-01 00:00:00\",\"EndDate\":\"2020-07-26 23:59:59\"}"}
    demo = OpenPlatformDemo()
    response = demo.mallcoo_post(url, json_data)
    response.content.decode()
    Active = json.loads(response.text)
    Active = Active['Data']['table'][0]['index_count']
    # print(response.status_code, response.text, sep='\n')
    return Active


def gender():  # 获取性别分布接口数据
    url = 'https://openapi10.mallcoo.cn/BI/BookMark/v1/Get/AttributeResult/'
    json_data = {"param": "{\"ProjectId\":552,\"APIId\":\"5e70422ef90e542d18686ee2\"}"}
    demo = OpenPlatformDemo()
    response = demo.mallcoo_post(url, json_data)
    response.content.decode()
    gender = json.loads(response.text)
    mangender = gender['Data']['table'][0]['index_count']
    womangender = gender['Data']['table'][1]['index_count']
    # print(gender)
    # print(response.status_code, response.text, sep='\n')
    return mangender, womangender


def card_level():  # 获取会员卡登记分布接口数据
    url = 'https://openapi10.mallcoo.cn/BI/BookMark/v1/Get/AttributeResult/'
    json_data = {"param": "{\"ProjectId\":552,\"APIId\":\"5e70422ef90e542d18686ee8\"}"}
    demo = OpenPlatformDemo()
    response = demo.mallcoo_post(url, json_data)
    response.content.decode()
    card_level = json.loads(response.text)
    Gold_card = card_level['Data']['table'][0]['index_count']
    Internal_card = card_level['Data']['table'][1]['index_count']
    Diamond_card = card_level['Data']['table'][2]['index_count']
    Wyatt_card = card_level['Data']['table'][3]['index_count']
    Merchant_employee_card = card_level['Data']['table'][4]['index_count']
    # print(gender)
    # print(response.status_code, response.text, sep='\n')
    return Gold_card, Internal_card, Diamond_card, Wyatt_card, Merchant_employee_card


def new_members_month():  # 获取本月新增会员
    now = datetime.date.today()
    this_month_start = datetime.datetime(now.year, now.month, 1)
    this_month_end = datetime.datetime(now.year, now.month, calendar.monthrange(now.year, now.month)[1])
    url = "http://bi.mp.mallcoo.cn/Behavior/Search?_c=1620368673441&projectID=552"

    payload = "{\"bookmarkID\":135930,\"target\":\"User\",\"disableLoading\":true,\"partSelector\":\"div.dashboard-contents[data-bookmark-id='135930'] > div[mc-loading]\",\"selectedEvents\":[{\"code\":\"25003\",\"selectedFields\":[\"distinct_totalcount\"],\"$hashKey\":\"object:451\"}],\"selectedGroups\":[],\"conditionGroup\":{\"operator\":\"and\",\"conditions\":[{\"code\":\"card_source\",\"operator\":\"equals\",\"values\":[\"æ°å¼å¡\"],\"type\":\"string\",\"uniqueId\":\"card_source_0_1583222441172\",\"rowCode\":\"card_source\",\"control\":{\"code\":\"tagsinput\",\"mode\":\"single\"},\"tagkey\":\"card_source_0_1583222441172\",\"hideRemove\":false},{\"code\":\"apply_type\",\"operator\":\"equals\",\"values\":[\"å¼å¡\"],\"type\":\"string\",\"uniqueId\":\"apply_type_1_1583222441172\",\"rowCode\":\"apply_type\",\"control\":{\"code\":\"tagsinput\",\"mode\":\"single\"},\"tagkey\":\"apply_type_1_1583222441172\",\"hideRemove\":false}]},\"timeRange\":[{\"model\":\"Relative\",\"dates\":[\"2018-11-01\",\"2018-11-12\"],\"value\":\"0\",\"unit\":\"Month\"},{\"dates\":[\"2020-03-01\",\"2020-02-29\"],\"model\":\"Absolute\",\"unit\":\"day\",\"value\":1}],\"contrastType\":\"circle\",\"displayMode\":\"card\",\"injectedArguments\":{\"conditionGroup\":{\"conditions\":[],\"operator\":\"and\"},\"timeRange\":[{\"model\":\"Relative\",\"dates\":[\"2021-05-01\",\"2021-05-07\"],\"value\":\"0\",\"unit\":\"Month\",\"isCustomDatePeriod\":false},{\"dates\":[\"2021-04-24\",\"2021-04-30\"],\"model\":\"Absolute\",\"unit\":\"day\",\"value\":1}],\"selectedGroups\":[],\"contrastType\":\"circle\"},\"forceRefresh\":true}"

    response = mallsession().request("POST", url, data=payload)
    response.content.decode()
    response = json.loads(response.text)
    new_members_month = response['current']['result'][0]['distinct_totalcount_25003']
    return new_members_month


def new_members_today():  # 获取昨日新增会员
    today = datetime.date.today()
    oneday = datetime.timedelta(days=1)
    yesterday = today - oneday  # 昨天日期
    url = 'https://openapi10.mallcoo.cn/BI/BookMark/v1/Get/EventResult/'
    json_data = {"param": "{\"ProjectId\":552,\"APIId\":\"5e70422ef90e542d18686eec\",\"StartDate\":\"" + str(
        yesterday) + "\",\"EndDate\":\"" + str(yesterday) + "\"}"}
    demo = OpenPlatformDemo()
    response = demo.mallcoo_post(url, json_data)
    response.content.decode()
    new_members_today = json.loads(response.text)
    new_members_today = new_members_today['Data']['table']['current']['Result'][0]['distinct_totalcount_25003']
    # print(response.status_code, response.text, sep='\n')
    return new_members_today


def get_shopmoney():  # 获取销采数据
    now = datetime.date.today()
    this_month_start = datetime.datetime(now.year, now.month, 1).strftime('%Y/%m/%d')
    this_month_end = datetime.datetime(now.year, now.month, calendar.monthrange(now.year, now.month)[1]).strftime(
        '%Y/%m/%d')
    loginurl = 'https://auth.xincheng.com/LoginService.ashx'
    listurl = 'http://passport.pri.xincheng.com/subsystems.do'
    logindata = {
        'lang': 'en - us',
        'systemCode': 'A07',
        'rememberPassword': 'false',
        'challengeNumber': '',
        'randomDate': '2020 - 07 - 28',
        '15': '34:50',
        'hidetxtPassword': 'lU/Q3OulShPF0iazGNk5O7YGzt9cMlFGiz5l/m73bCJ9WSVGCtqmnHroP6IjSat4m7HTQlMn9VGVbAssdYyR4BOsEdjB3lTY4wmzqd8gfwV5YpbaeoERAzuwpl7QzCyjEnV34Nu7eMlyXZrJLxdGLEdVxdKetMMhJlT2y5sKL1SrpPW4i5sJRC2uH2Jh2qeWkOEW87C8QF9Tyr+Hhyx8ZjH0RbtKW82gLG+edUxls2nXZ6rMkZHmOh9QrPc2/ORlIYAHItYHyd098/6+afAQavKHcmh8kGmmNW0uZYOs57ZJxwLpJ2NoDOX+YWgS57Wh6ceQXqZR3Gt7b+dDN7M1gw==',
        'txtIsTrustAccessor': 'True',
        'txtUserName': 'wangrui20',
    }
    loginheader = {
        'Referer': 'https://auth.xincheng.com/?challengeNumber=ZGY5eGpsaGt5NTB0cWRlcHJ0c2h1OXVuMDBlMHFnbXMwN2JmZGEzYmEyNTlsaHFtYXN5MHlheWRjOGNsZmIyZjF4ejJ0b3BvbW1mMHl4ZTR4b2ZlcnlrdGVsemRncG1yY3MybzVicmxyOHlqdDRsbTgzb2I5d2tpOGx3dnlvMW9zOXJ6azh4OWRoYnVkd253b2pubHNpbmN2Y3ZvOWttNjBtcW14MWV2NDFnOHpmc2s4bHN2ZmN3aGk0Y2RhZXR4c2JtbjJmYmZ6cWV1MWlibnE2OGUyOTd4azBpMGd5ODlrMmFqM2w3djMxb2d5c3N1bnFnYWFjNHV6YWluZWY5cA==&flag=3&systemCode=A07&RetutnUrl=http%3A%2F%2Fekp.xincheng.com%2Fsys%2Fportal%2Fpage.jsp',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36',
    }
    session = requests.session()
    session.post(loginurl, data=logindata, headers=loginheader)
    tokenreq = session.get(listurl)
    tokenreq.content.decode()
    tokenreq = json.loads(tokenreq.text)
    tokenreq = tokenreq['body']['user']['orgId']
    url = 'http://databiapi.web.pri.xincheng.com/shop/shopAnalyze/getShopEntitySaleInfo?token=misUser' + tokenreq + ''

    header = {
        'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_15_6) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 84.0.4147.89Safari / 537.36',
        'Referer': 'http://databi.pri.xincheng.com/',
    }
    data2 = {
        'floors': '',
        'from': str(this_month_start),
        'to': str(this_month_end),
        'pageIndex': '1',
        'pageSize': '10',
        'shopTypes': '',
        'type': '0',
        'shopEntityIds': '',
        'id': tokenreq,
        'orderKey': 'claimMoneyTotal',
        'orderBy': 'desc',
        'terminalStatus': '',
        'effectiveTerminalFlag': '',
    }

    mouney = session.post(url, headers=header, data=data2)
    mouney.content.decode()
    mouney = json.loads(mouney.text)
    mouney = mouney['data']['data']
    q = int(mouney[0]['claimMoneyTotal'] / 10000)
    qname = mouney[0]['entityName']
    w = int(mouney[1]['claimMoneyTotal'] / 10000)
    wname = mouney[1]['entityName']
    e = int(mouney[2]['claimMoneyTotal'] / 10000)
    ename = mouney[2]['entityName']
    r = int(mouney[3]['claimMoneyTotal'] / 10000)
    rname = mouney[3]['entityName']
    t = int(mouney[4]['claimMoneyTotal'] / 10000)
    tname = mouney[4]['entityName']
    y = int(mouney[5]['claimMoneyTotal'] / 10000)
    yname = mouney[5]['entityName']
    u = int(mouney[6]['claimMoneyTotal'] / 10000)
    uname = mouney[6]['entityName']
    i = int(mouney[7]['claimMoneyTotal'] / 10000)
    iname = mouney[7]['entityName']
    o = int(mouney[8]['claimMoneyTotal'] / 10000)
    oname = mouney[8]['entityName']
    p = int(mouney[9]['claimMoneyTotal'] / 10000)
    pname = mouney[9]['entityName']
    name = qname.split("_")[0], wname.split("_")[0], ename.split("_")[0], rname.split("_")[0], tname.split("_")[0], \
           yname.split("_")[0], uname.split("_")[0], iname.split("_")[0], oname.split("_")[0], pname.split("_")[0]
    money = q, w, e, r, t, y, u, i, o, p
    return money, name


def get_Allmoney():
    now = datetime.date.today()
    this_month_start = datetime.datetime(now.year, now.month, 1).strftime('%Y/%m/%d')
    this_month_end = datetime.datetime(now.year, now.month, calendar.monthrange(now.year, now.month)[1]).strftime(
        '%Y/%m/%d')
    loginurl = 'https://auth.xincheng.com/LoginService.ashx'
    listurl = 'http://passport.pri.xincheng.com/subsystems.do'
    logindata = {
        'lang': 'en - us',
        'systemCode': 'A07',
        'rememberPassword': 'false',
        'challengeNumber': '',
        'randomDate': '2021-05-23',
        '15': '34:50',
        'hidetxtPassword': 'lU/Q3OulShPF0iazGNk5O7YGzt9cMlFGiz5l/m73bCJ9WSVGCtqmnHroP6IjSat4m7HTQlMn9VGVbAssdYyR4BOsEdjB3lTY4wmzqd8gfwV5YpbaeoERAzuwpl7QzCyjEnV34Nu7eMlyXZrJLxdGLEdVxdKetMMhJlT2y5sKL1SrpPW4i5sJRC2uH2Jh2qeWkOEW87C8QF9Tyr+Hhyx8ZjH0RbtKW82gLG+edUxls2nXZ6rMkZHmOh9QrPc2/ORlIYAHItYHyd098/6+afAQavKHcmh8kGmmNW0uZYOs57ZJxwLpJ2NoDOX+YWgS57Wh6ceQXqZR3Gt7b+dDN7M1gw==',
        'txtIsTrustAccessor': 'True',
        'txtUserName': 'wangrui20',
    }
    loginheader = {
        'Referer': 'https://auth.xincheng.com/?challengeNumber=ZGY5eGpsaGt5NTB0cWRlcHJ0c2h1OXVuMDBlMHFnbXMwN2JmZGEzYmEyNTlsaHFtYXN5MHlheWRjOGNsZmIyZjF4ejJ0b3BvbW1mMHl4ZTR4b2ZlcnlrdGVsemRncG1yY3MybzVicmxyOHlqdDRsbTgzb2I5d2tpOGx3dnlvMW9zOXJ6azh4OWRoYnVkd253b2pubHNpbmN2Y3ZvOWttNjBtcW14MWV2NDFnOHpmc2s4bHN2ZmN3aGk0Y2RhZXR4c2JtbjJmYmZ6cWV1MWlibnE2OGUyOTd4azBpMGd5ODlrMmFqM2w3djMxb2d5c3N1bnFnYWFjNHV6YWluZWY5cA==&flag=3&systemCode=A07&RetutnUrl=http%3A%2F%2Fekp.xincheng.com%2Fsys%2Fportal%2Fpage.jsp',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36',
    }
    header = {
        'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_15_6) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 84.0.4147.89Safari / 537.36',
        'Referer': 'http://databi.pri.xincheng.com/',
    }
    session = requests.session()
    session.post(loginurl, data=logindata, headers=loginheader)
    tokenreq = session.get(listurl)
    tokenreq.content.decode()
    tokenreq = json.loads(tokenreq.text)
    tokenreq = tokenreq['body']['user']['orgId']
    url2 = 'http://databiapi.web.pri.xincheng.com/shop/global/getImportantKey?token=misUser' + tokenreq + ''
    data3 = {
        'id': tokenreq,
        'from': str(this_month_start),
        'to': str(this_month_end),
        'floors': '',
        'shopTypes': '',
        'shopEntityIds': '',
    }
    Allmouney = session.post(url2, headers=header, data=data3)
    Allmouney.content.decode()
    Allmouney = json.loads(Allmouney.text)
    Allmouney = Allmouney['data'][0]['descValue']
    return Allmouney


def Consumption_points():  # 获取会员消费金额
    now = datetime.date.today()
    this_month_start = datetime.datetime(now.year, now.month, 1)
    this_month_end = datetime.datetime(now.year, now.month, calendar.monthrange(now.year, now.month)[1]).strftime(
        '%Y-%m-%d')
    url = 'https://openapi10.mallcoo.cn/BI/BookMark/v1/Get/EventResult/'
    json_data = {
        "param": "{\"ProjectId\":552,\"APIId\":\"5e70422ef90e542d18686ee5\",\"StartDate\":\"" + str(
            this_month_start) + "\",\"EndDate\":\"" + str(this_month_end) + " 23:59:59\"}"
    }
    demo = OpenPlatformDemo()
    response = demo.mallcoo_post(url, json_data)
    response.content.decode()
    Consumption_points = json.loads(response.text)
    Consumption_points = Consumption_points['Data']['table']['current']['Result'][0]['payment_amount_sum_25001']
    Consumption_points = int(Consumption_points / 10000)
    # print(response.status_code, response.text, sep='\n')
    return Consumption_points


def get_floor_Consumption_points():  # 获取各楼层会员消费金额数据
    session = mallsession()
    AllConsumption_points = int(Consumption_points() * 10000)
    url = "http://bi.mp.mallcoo.cn/Behavior/Search?_c=1599886711183&projectID=552"
    payload = "{\"selectedEvents\":[{\"code\":\"25001\",\"selectedFields\":[\"payment_amount,sum\"],\"$hashKey\":\"object:386\"}],\"selectedGroups\":[{\"code\":\"shop_floorname\",\"text\":\"åæ·æ¥¼å±\",\"type\":\"string\",\"$hashKey\":\"object:390\"}],\"conditionGroup\":{\"operator\":\"and\",\"conditions\":[]},\"timeRange\":[{\"model\":\"Relative\",\"dates\":[\"2020-09-01\",\"2020-09-12\"],\"value\":\"0\",\"unit\":\"Month\",\"isCustomDatePeriod\":false,\"lastMonthReciprocal\":0,\"thisMonthReciprocal\":0},{\"model\":\"Absolute\",\"dates\":[\"2020-07-10\",\"2020-07-24\"],\"value\":1,\"unit\":\"Week\",\"isCustomDatePeriod\":false,\"lastMonthReciprocal\":0,\"thisMonthReciprocal\":0}],\"contrastType\":\"nocontrast\",\"target\":\"User\",\"direction\":\"desc\",\"top\":null,\"ForceRefresh\":false}"
    response = session.request("POST", url, data=payload)
    response.content.decode()
    data = json.loads(response.text)
    data = data['current']['result']
    onefloor = '{:.2f}'.format(data[0]['payment_amount_sum_25001'] / AllConsumption_points * 100)
    twofloor = '{:.2f}'.format(data[1]['payment_amount_sum_25001'] / AllConsumption_points * 100)
    threefloor = '{:.2f}'.format(data[2]['payment_amount_sum_25001'] / AllConsumption_points * 100)
    fourfloor = data[3]['payment_amount_sum_25001']
    fivefloor = data[4]['payment_amount_sum_25001']
    fourfloor = '{:.2f}'.format((fourfloor + fivefloor) / AllConsumption_points * 100)
    datas = onefloor, twofloor, threefloor, fourfloor
    floordata = []
    for i in datas:
        a = i
        floordata.append(a)
    return floordata


def Proportion_of_consumption():
    monthAllmoney = get_Allmoney()
    mallcoomoney = Consumption_points()
    Proportion = float(mallcoomoney / monthAllmoney * 100)
    Proportion = float('%.2f' % Proportion)
    Proportion = str(Proportion)
    return Proportion
